package com.edu.admin.common;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.edu.admin.utils.Query;
import com.github.pagehelper.PageInfo;

/**
 * 控制器基类
 *
 */
@SuppressWarnings("rawtypes")
public class BaseController<BService extends BaseService, Entity> {

	@Autowired
	protected HttpServletRequest request;

	@Autowired
	protected BService baseService;

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "", method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<Entity> add(@RequestBody Entity entity) {
		baseService.insertSelective(entity);
		return ResponseEntity.ok(entity);
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Entity> get(@PathVariable("id") String id) {
		Entity o = (Entity) baseService.selectByPrimaryKey(id);
		return ResponseEntity.ok(o);
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
	@ResponseBody
	public ResponseEntity<String> update(@RequestBody Entity entity) {
		baseService.updateByPrimaryKeySelective(entity);
		return ResponseEntity.ok(null);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseBody
	public ResponseEntity<String> remove(@PathVariable("id") String id) {
		baseService.deleteByPrimaryKey(id);
		return ResponseEntity.ok(null);
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/all", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<List<Entity>> all() {
		return ResponseEntity.ok().body(baseService.selectListAll());
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/page", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<PageInfo<Entity>> list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		Query query = new Query(params);
		List<Entity> list = baseService.selectByQuery(query);
		PageInfo<Entity> p = new PageInfo<Entity>(list);
		return ResponseEntity.ok(p);
	}

}
